var _ = require('lodash');
var mkdirp = require('mkdirp');
var fs = require('fs');

module.exports = function(opt) {
  if (!opt.enode) throw new Error('Enode not provided (node index.js <mode> <enode>)');
  var client = require('./clients')(opt);

  mkdirp.sync('./out');
  opt.output = './out/' + (opt.output || 'sync-data.js')
  fs.writeFileSync(opt.output, 'export default');
  require('./profileClientSync')(client, opt, function(err) {
    if (err) console.log(err);
    handleExit(err, client);
  });

  function handleExit(err, client) {
    if (err) console.log(err);
    if (client && client.process) {
      console.log('kill client:', client.process.pid);
      client.process.kill();
      _.each(client.associatedPids, function(pid) {
        console.log('Kill child process:', pid);
        process.kill(pid);
      });
    }
    process.exit();
  }

  process.on('exit', handleExit);
  process.on('SIGINT', handleExit);
  process.on('uncaughtException', handleExit);
};
